package com.yh.tea.utiity;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yh.tea.entity.User;
import com.yh.tea.service.UserService;
import com.yh.tea.service.impl.UserServiceImpl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.util.Calendar;
import java.util.HashMap;
@Configuration
public class JWTUtility {

    @Value("${jwt.signature}")
    private String sign;

    private UserService userService;
    //生成token
    public  String createJWT(User user){
        //头
        HashMap<String,Object> headerMap=new HashMap();
        //过期时间1天
        Calendar expires=Calendar.getInstance();
        expires.add(Calendar.SECOND,10*60*60*24);
        String token= JWT.create().withHeader(headerMap)
                .withClaim("id",user.getId())
                .withClaim("userName",user.getUserName())
                .withClaim("password",user.getPassword())
                .withExpiresAt(expires.getTime())
                .sign(Algorithm.HMAC256(sign));
        return token;
    }

    public String getSign() {
        return sign;
    }

    public  User ReadJWT(String token){
        User user=new User();
        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(sign)).build();
        DecodedJWT decodedJWT=jwtVerifier.verify(token);
        user.setId(decodedJWT.getClaim("id").asLong());
        user.setUserName(decodedJWT.getClaim("userName").asString());
        user.setPassword(decodedJWT.getClaim("password").asString());
        return user;
    }


    public  Boolean jwtVerify (String token) {
        //获得一个jwtParse对象用来解密,通过程序员设置的salt和token解密如果能够解密就证明是正确的token，否则报出异常

        return true;
    }
}
